package com.xiashitech.agent.rule.usermatch.inst;

import com.google.auto.service.AutoService;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.rule.usermatch.base.UserInfoMatchRule;
import com.xiashitech.agent.utils.SessionUtil;
import com.xiashitech.interfaces.agent.dto.AgentConfigDTO;

import java.util.Date;
import java.util.Optional;

/**
 * 获取request里的复杂对象的userid
 * @param <REQUEST>
 */
//@AutoService(UserInfoMatchRule.class)
public class XSOgnlForRequestUserMatch<REQUEST> implements UserInfoMatchRule<REQUEST> {
    @Override
    public UserRequest extractUserInfo(REQUEST request) {
        if(request == null || !request.getClass().getName().equals("javax.servlet.http.HttpServletRequest") || !request.getClass().getName().equals("org.springframework.web.context.request.ServletWebRequest")) {
            return UserRequest.builder().build();
        }
        UserRequest userRequest = UserRequest.builder().requestDate(String.valueOf(new Date().getTime())).build();
        try {
            Object httpSession = null;
            if(request.getClass().getName().equals("javax.servlet.http.HttpServletRequest")) {
                httpSession = request.getClass().getMethod("getSession",new Class[]{boolean.class}).invoke(request,false);
            } else if(request.getClass().getName().equals("org.springframework.web.context.request.ServletWebRequest")) {
                Object httpRequest = request.getClass().getMethod("getRequest").invoke(request);
                httpSession = httpRequest.getClass().getMethod("getSession",new Class[]{boolean.class}).invoke(httpRequest,false);
            }
            if(httpSession != null) {
                Object sessionId = httpSession.getClass().getMethod("getId").invoke(httpSession);
                if(sessionId != null) {
                    userRequest.setSessionId(sessionId.toString());
                }
            }
            Optional<String> useridOptional = SessionUtil.getUseridFromSession(httpSession, AgentConfigDTO.getConfig().getUseridpath().get(StartConfig.getParamValueFromKey(StartConfig.systemId)));
            if(useridOptional.isPresent()) {
                userRequest.setUserid(useridOptional.get());
            }
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
        return userRequest;
    }

    @Override
    public Integer getOrder() {
        return 3;
    }
}
